
import router from '@/router/index.ts'
import type { RouteLocationNormalizedLoaded,RouteRecordNormalized } from 'vue-router'
//\src\layout\components\TagsView\index.vue addTags可以设置标题
export interface TagsViewState {
  visitedViews: RouteLocationNormalizedLoaded[]
  cachedViews: Set<string>
  iframeViews: RouteLocationNormalizedLoaded[]
  selectedTag?: RouteLocationNormalizedLoaded
}
const useTagsViewStore = defineStore(
  'tags-view',
  {
    state: (): TagsViewState => ({
      visitedViews: [],
      cachedViews:new Set(),
      iframeViews: [],
      selectedTag: undefined
    }),

    getters:{
        getVisitedViews(): RouteLocationNormalizedLoaded[] {
          return this.visitedViews
        },
        getCachedViews(): string[] {
          return Array.from(this.cachedViews)
        },
        getSelectedTag(): RouteLocationNormalizedLoaded | undefined {
          return this.selectedTag
        }
    },

    actions: {

      setTitle(title: string, path?: string) {
          for (const v of this.visitedViews) {
            if (v.path === (path ?? this.selectedTag?.path)) {
              v.meta.title = title
              break
            }
          }
        },
        // 设置当前选中的 tag
      setSelectedTag(tag: RouteLocationNormalizedLoaded) {
        this.selectedTag = tag
      },

      //新增页签
      addView(view) {
        this.addVisitedView(view)
        this.addCachedView(view)
      },
      addIframeView(view) {
        if (this.iframeViews.some(v => v.path === view.path)) return
        this.iframeViews.push(
          Object.assign({}, view, {
            title: view.meta.title || 'no-name'
          })
        )
      },
      //将新增的页签放入已访问页签
      addVisitedView(view) {
        if (this.visitedViews.some(v => v.path === view.path)) return
        this.visitedViews.push(
          Object.assign({}, view, {
            title: view.meta.title || 'no-name'
          })
        )
      },
      addCachedView(view: RouteLocationNormalizedLoaded) {
        if (view.name && typeof view.name === 'string') {
          const cachedViewsArray = Array.from(this.cachedViews);
          if (cachedViewsArray.includes(view.name)) return
          if (!view.meta.noCache) {
            this.cachedViews.add(view.name)
          }
        }

      },
      refreshCachedView() {
            const cacheMap: Set<string> = new Set()
            
            for (const v of this.visitedViews) {
              const item = v
              const needCache = !item.meta?.noCache
              if (!needCache) {
                continue
              }
              const name = item.name as string
              if (name) {
                cacheMap.add(name)
              }
            }
            
            // 只有当缓存发生变化时才更新
            if (Array.from(this.cachedViews).sort().toString() === Array.from(cacheMap).sort().toString()) {
              return
            }
      
            this.cachedViews = cacheMap
    },
      // delView(view) {
      //   return new Promise(resolve => {
      //     this.delVisitedView(view)
      //     this.delCachedView(view)
      //     resolve({
      //       visitedViews: [...this.visitedViews],
      //       cachedViews: [...this.cachedViews]
      //     })
      //   })
      // },


      //关闭页签
       delView(view: RouteLocationNormalizedLoaded) {
        this.delVisitedView(view)
        this.delCachedView(view)
        return {
          //返回的是一个全新的数组，这样就不会影响原始数据，实现了数据的不可变性
          visitedViews: [...this.visitedViews],
          cachedViews: [...this.cachedViews]
        }
        
      },
      //关闭页签要从已访问的页签中移除
      delVisitedView(view: RouteLocationNormalizedLoaded) {

        for (const [i, v] of this.visitedViews.entries()) {
            if (v.path === view.path) {
              this.visitedViews.splice(i, 1)
              break
            }
          }
        return {
          visitedViews: [...this.visitedViews]
        }

      },
      delIframeView(view: RouteLocationNormalizedLoaded) {
          this.iframeViews = this.iframeViews.filter(item => item.path !== view.path)
          return {
            iframeViews: [...this.iframeViews]
          }
        
      },
      delCachedView(view: RouteLocationNormalizedLoaded) {
        if (view.name && typeof view.name === 'string') {
            const index = this.getCachedViews.indexOf(view.name);
            if (index > -1) {
              this.cachedViews.delete(this.getCachedViews[index]);
            }
        }
      },
      delOthersViews(view: RouteLocationNormalizedLoaded) {
        this.delOthersVisitedViews(view)
        this.delOthersCachedViews(view)


      },
      delOthersVisitedViews(view: RouteLocationNormalizedLoaded) {
          this.visitedViews = this.visitedViews.filter(v => {
            //yudao用的fullpath
            return v.meta.affix || v.path === view.path
          })
          this.iframeViews = this.iframeViews.filter(item => item.path === view.path)

      },
      delOthersCachedViews(view) {

        const cacheMap: Set<string> = new Set()

        if (view.name && typeof view.name === 'string') {
          cacheMap.add(view.name);
          this.cachedViews = cacheMap;
        }

        return {
          cachedViews: [...this.cachedViews]
        }


      },
      delAllViews() {
        this.delAllVisitedViews()
        this.delAllCachedViews()
      },
      delAllVisitedViews() {
        const affixTags = this.visitedViews.filter(tag => tag.meta.affix)
        this.visitedViews = affixTags
        this.iframeViews = []
        return {
          //返回的是一个全新的数组，这样就不会影响原始数据，实现了数据的不可变性
          visitedViews: [...this.visitedViews],
          
        }
      },
      delAllCachedViews() {
        this.cachedViews = new Set()
        return {
          cachedViews: [...this.cachedViews]
        }

      },
      updateVisitedView(view) {
        for (let v of this.visitedViews) {
          if (v.path === view.path) {
            v = Object.assign(v, view)
            break
          }
        }
      },
      delRightTags(view: RouteLocationNormalizedLoaded) {
        
            const index = this.visitedViews.findIndex(v => v.path === view.path);
            if (index === -1) return;

            const cachedViewsArray = [...this.getCachedViews]; // 创建缓存数组副本避免直接修改原始数据
            const removedViews:Array<RouteLocationNormalizedLoaded> = []; // 收集待移除视图

            // 使用slice分离右侧标签，避免在filter中处理复杂逻辑
            const keepViews = this.visitedViews.slice(0, index + 1);
            const rightViews = this.visitedViews.slice(index + 1);

            // 筛选需要保留的固定标签
            const affixViews = rightViews.filter(item => item.meta?.affix);
            this.visitedViews = [...keepViews, ...affixViews];

            // 处理右侧非固定标签
            rightViews.forEach(item => {
              if (!item.meta?.affix) {
                removedViews.push(item);
                
                // 从缓存中移除
                if (item.name && typeof item.name === 'string') {
                  const cachedIndex = cachedViewsArray.indexOf(item.name);
                  if (cachedIndex > -1) {
                    cachedViewsArray.splice(cachedIndex, 1);
                  }
                }
                
                // 处理iframe视图
                if (item.meta?.link) {
                  const iframeIndex = this.iframeViews.findIndex(v => v.path === item.path);
                  if (iframeIndex > -1) {
                    this.iframeViews.splice(iframeIndex, 1);
                  }
                }
              }
            });

            this.cachedViews = new Set(cachedViewsArray);


        return {
          //返回的是一个全新的数组，这样就不会影响原始数据，实现了数据的不可变性
          visitedViews: [...this.visitedViews]
        }
          
        
      },
      delLeftTags(view: RouteLocationNormalizedLoaded) {
       
          const index = this.visitedViews.findIndex(v => v.path === view.path)
          if (index === -1) {
            return
          }
          const cachedViewsArray = this.getCachedViews;
          this.visitedViews = this.visitedViews.filter((item, idx) => {
            //这里标记的左侧
            if (idx >= index || (item.meta && item.meta.affix)) {
              return true
            }

            if (item.name && typeof item.name === 'string') {
             
                const i = cachedViewsArray.indexOf(item.name)
                if (i > -1) {
                  cachedViewsArray.splice(i, 1)
                }
            }
            
            if(item.meta.link) {
              const fi = this.iframeViews.findIndex(v => v.path === item.path)
              this.iframeViews.splice(fi, 1)
            }
            return false
          })
          this.cachedViews = new Set(cachedViewsArray)
        return {
          //返回的是一个全新的数组，这样就不会影响原始数据，实现了数据的不可变性
          visitedViews: [...this.visitedViews]
        }
      },

      
    }
  })

export default useTagsViewStore
